import { BasicDrawer, useDrawerInner } from "@/components/Drawer";
import { BasicForm, FormSchema, useForm } from "@/components/Form";
import { ObjectApi } from "@/api/erp/drug/object";
import { message } from "antd";
import { useTranslation } from "react-i18next";
import { useState, useMemo } from "react";
let reload: Function;
let objId: any;
const index = (props: { register: Fn }) => {
	const [isUpdated, setIsUpdated] = useState(false);
	const { t } = useTranslation();
	const en_vi = "drugStorage.drugManagement.other";
	const formSchema: FormSchema[] = [
		{
			label: t(`${en_vi}.objName`),
			field: "objName",
			component: "Input"
		},
		{
			label: t(`${en_vi}.sourceId`),
			field: "sourceId",
			component: "Input"
		},
		{
			label: t(`${en_vi}.objType`),
			field: "objType",
			component: "InputNumber"
		},
		{
			label: t(`${en_vi}.grpNo`),
			field: "grpNo",
			component: "Input"
		},
		{
			label: t(`${en_vi}.whsNo`),
			field: "whsNo",
			component: "Input"
		},
		{
			label: t(`${en_vi}.objRatio`),
			field: "objRatio",
			component: "InputNumber"
		},
		{
			label: t(`${en_vi}.hideFlag`),
			field: "hideFlag",
			component: "Select",
			componentProps: {
				options: [
					{
						label: t("felix_ui.open"),
						value: 0
					},
					{
						label: t("felix_ui.close"),
						value: 1
					}
				]
			}
		}
	];
	const getTitle = useMemo(() => {
		return isUpdated ? t("felix_ui.edit") : t("felix_ui.add");
	}, [isUpdated]);
	const [register, { validateFields, setFieldsValue, resetFields }] = useForm({
		schemas: formSchema,
		labelWidth: 120,
		baseColProps: {
			span: 24
		}
	});
	const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(props.register, data => {
		reload = data.reload;
		objId = data.record?.objId;
		resetFields();
		setDrawerProps({ confirmLoading: true });
		setIsUpdated(!!data?.isUpdated);
		setFieldsValue({
			...data.record
		});
		setDrawerProps({ confirmLoading: false });
	});
	const handleSubmit = async () => {
		const formValue = await validateFields();
		let res;
		if (isUpdated) {
			formValue.objId = objId;
			res = await ObjectApi.updateObject(formValue);
		} else {
			res = await ObjectApi.createObject(formValue);
		}
		if (!res) {
			message.error(t("viewComponents.patientInformation.additionFailed"));
			return;
		}
		message.success(t("viewComponents.patientInformation.successfullyAdded"));
		closeDrawer();
		reload();
	};

	return (
		<BasicDrawer title={getTitle} showFooter={true} {...props} register={registerDrawer} ok={handleSubmit}>
			<BasicForm register={register} labelWrap={true}></BasicForm>
		</BasicDrawer>
	);
};
export default index;
